//
//  ZHLEENetWorkTools.swift
//  ZHLEE_Blog_Swift_Pro
//
//  Created by ZHLEEBlander on 15/10/22.
//  Copyright © 2015年 ZHLEEBlander. All rights reserved.
//

import UIKit
import AFNetworking

enum ZHLEENetWorkToolsRequestType: String{

    case GET = "GET"
    case POST = "POST"
}

class ZHLEENetWorkTools: NSObject {
    
    class func request(type: ZHLEENetWorkToolsRequestType,url: String,var params: [String: AnyObject]?,accessToken: Bool = true,success: ((result: [String: AnyObject])->()),failure: (error: NSError)->()) {
        
        //可以在这个地方统一添加accesstoken的参数

        if accessToken {
        
            if params == nil {
            
                params = [String: AnyObject]()
            }
            params!["access_token"] = ZHLEEUserAccount.loadAccount()?.access_token
        }
        
        let manager = AFHTTPSessionManager()
        //添加contentType
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
      
        let successCallBack = {(dataTask:NSURLSessionDataTask, result:AnyObject) -> Void in
            
            if let res = (result as? [String: AnyObject]){
                //数据回调
                success(result: res)
            }else{
                
                //如果类型不对
                failure(error: NSError(domain: "myweibo", code: 10001, userInfo: ["errorMsg" : "The type of result isn't [String: AnyObject]"]))
            }
        }
        
        let failureCallBack = {(dataTask:NSURLSessionDataTask, error:NSError) -> Void in
        
            //连接失败
            failure(error: error)
        }
        
        if type == .GET {
        
            manager.GET(url, parameters: params, success: successCallBack, failure: failureCallBack)
        }else{
        
            manager.POST(url, parameters: params, success: successCallBack, failure: failureCallBack)
        }
    }
}
